package com.sdk.paas.core.utils;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 描述
 * <p>
 * 签名工具类
 */
public class SignUtil {
    /**
     * MD5后再转成base64
     *
     * @param str
     * @author limaosheng
     * @create 17:57 2022/3/28
     */
    public static String md5ThenBase64(String str) {
        return Base64.getEncoder().encodeToString(DigestUtils.md5(str));
    }

    /**
     * 敏感信息脱敏加密
     *
     * @param secret
     * @param str
     * @return
     */
    public static String aes(String secret, String str) {
        return SecureUtil.aes(secret.getBytes(StandardCharsets.UTF_8)).encryptBase64(str);
    }

    /**
     * 签名
     *
     * @param data   签名内容
     * @param secret 秘钥
     * @author limaosheng
     * @create 9:45 2022/8/9
     */
    public static String sign(String data, String secret) {
        if (StrUtil.isEmpty(data) || StrUtil.isEmpty(secret)) {
            return "";
        }
        byte[] key = secret.getBytes();
        return sign(data, key);
    }

    public static String sign(String data, byte[] secret) {
        if (StrUtil.isEmpty(data) || null == secret) {
            return "";
        }
        HMac hMac = new HMac(HmacAlgorithm.HmacSHA256, secret);
        return hMac.digestHex(data).toUpperCase();
    }
}
